module service.ContactsService;

import std.stdio;
import message.MsgDefine;
import model;
import repository;
import hunt.logging;
import std.conv : to;
import service.GroupService;

class ContactsService {

  static ContactRES getContact(ulong userId,long timestamp)
  {
    auto userRepo = new UserRepository();
    auto friendRepo = new FriendRepository();
    auto friendApplyRepo = new FriendApplyRepository();
    auto groupApplyRepo = new GroupApplyRepository();
    ContactRES res = new ContactRES();
    res.clientId = userId;
    if (timestamp == 0)
    {
      auto friends = friendRepo.findAllByID(cast(int)userId);
      foreach(f ; friends)
      {
        auto user = userRepo.findById(f.friendId);
        if(user is null)
        {
          logWarning("not this userinfo " , f.friendId);
          continue;
        }
        auto resUser = toUser(user);
        resUser.lastMsgRead = f.updated;
        resUser.aliasName = f.aliasName;
        resUser.chatId = to!string(f.chatId);
        resUser.src = cast(ContactApplySrc)f.src;
        res.users ~= resUser;
      }
      auto friendApplys = friendApplyRepo.getUntreated(to!string(userId));
      auto groupApplys = groupApplyRepo.getUntreated(to!string(userId));
      res.contactApplys = ContactsService.toApplyContact(friendApplys);
      res.groupApplys = ContactsService.toApplyGroup(groupApplys);
      res.groups = GroupService.getAllGroupMember(to!string(userId));
      foreach(GroupInfo mm ; res.groups)
      {
          logInfo("chatId : %s" ,mm.groupId);
          logInfo("IDs : %s",mm.memberId);
          logInfo("================================");
      }

    }
    return res;
  }

    static ApplyContact[] toApplyContact(FriendApply[] applys)
    {
        ApplyContact[] rt;
        foreach (FriendApply apply ; applys)
        {
            ApplyContact apl = new ApplyContact;
            apl.fromId = to!string(apply.userId);
            apl.toId = to!string(apply.friendId);
            apl.chatId =  to!string(apply.id);
            apl.message = apply.message;
            apl.timestamp = apply.created;
            rt ~= apl;
        }
        return rt;
    }

    static ApplyGroup[] toApplyGroup(GroupApply[] applys)
    {
        ApplyGroup[] rt;
        foreach (GroupApply apply ; applys)
        {
             ApplyGroup apl = new ApplyGroup;
             apl.fromId = to!string(apply.fromId);
             apl.groupId = to!string(apply.groupId);
             apl.username = apply.aliasName;
             apl.newMember = to!string(apply.newMember);
             apl.destination = to!string(apply.toId);
             rt ~= apl;
        }
        return rt;
    }

}

